package com.wpq.netty.discard;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 *  丢弃任何进入的数据
 */
public class DiscardServer {
    private int port;
    public  DiscardServer(int port){
        this.port=port;
    }
    public void run() throws Exception{
        EventLoopGroup bossGroup = new NioEventLoopGroup();  //用来处理I/O操作的多线程事件循环器  用来接收进来的连接
        EventLoopGroup workerGroup = new NioEventLoopGroup(); //用来处理已经接收的连接
        try {
            ServerBootstrap b= new ServerBootstrap(); //是一个启动NIO服务的辅助启动类
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    //ChannelInitializer 是一个特殊的处理类，他的目的是帮助使用者配置一个新的 Channel
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new DiscardServerHandler());
                        }
                    }).option(ChannelOption.SO_BACKLOG,128) //option() 是提供给NioServerSocketChannel 用来接收进来的连接
                    .childOption(ChannelOption.SO_KEEPALIVE,true); //childOption() 是提供给由父管道 ServerChannel 接收到的连接
            //绑定端口，开始接收进来的连接
            ChannelFuture f=b.bind(port).sync();
            //等待服务器 socket 关闭
            f.channel().closeFuture().sync();
        }finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

    }

    public static void main(String [] args) throws Exception{
        int port;
        if(args.length>0){
            port =Integer.parseInt(args[0]);

        }else{
            port=8089;
        }
        new DiscardServer(port).run();
    }
}

